<template>
  <view>
    <view class="item">
      <view class="let">{{ label }}</view>
      <view class="rig">
        <view class="input">
          <input
            class="inp"
            :value="value"
            :type="inputType"
            :placeholder="placeholder"
            :placeholder-style="placeholderStyle"
            @input="inputChange"
          />
        </view>

        <view
          :class="['yzm', hasRequired ? 'disabled' : '']"
          v-if="isGetCode"
          @click="getCode"
        >
          <u-verification-code
            :seconds="seconds"
            @end="end"
            @start="start"
            ref="uCode"
            @change="codeChange"
          ></u-verification-code>
          {{ hasRequired ? tips : "获取验证码" }}</view
        >
      </view>
    </view>
  </view>
</template>

<script>
import { regMobile } from "@/common/regExp";

export default {
  props: {
    label: {
      type: String,
      default: ""
    },
    inputType: {
      type: String,
      default: "text"
    },
    placeholderStyle: {
      type: String,
      default: "color:#8c8c8c;"
    },
    placeholder: {
      type: String,
      default: "请输入"
    },
    isGetCode: {
      type: Boolean,
      default: false
    },
    value: {
      type: [String, Number],
      default: ""
    },
    phone: {
      type: [String, Number],
      default: ""
    },
    code_type: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
      hasRequired: false,
      seconds: 60,
      tips: ""
    };
  },

  methods: {
    inputChange(e) {
      this.$emit("update:value", e.detail.value);
    },

    codeChange(text) {
      this.tips = text;
    },

    end() {
      this.hasRequired = false;
    },

    getCode() {
      let { code_type, hasRequired, phone } = this;
      if (hasRequired) return false;
      this.$u.throttle(async () => {
        if (!phone) return this.$u.toast("请输入手机号");
        if (!regMobile(phone)) return this.$utils.toast("请填写正确的手机号~");

        if (this.$refs.uCode.canGetCode) {
          const res = await this.$allrequest.user.sms_code(
            { code_type, phone },
            true
          );
          if (!res.code) {
            this.hasRequired = true;
            this.$refs.uCode.start();
          }
        } else {
          this.$u.toast("倒计时结束后再发送");
        }
      }, 1000);
    }
  }
};
</script>

<style lang="scss" scoped>
.item {
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  border-top: 1px solid #efefef;
  font-size: 32rpx;
  color: #262626;

  .let {
    min-width: 160rpx;
  }

  .rig {
    display: flex;
    align-items: center;
    overflow: hidden;
    flex: 1;
    overflow: hidden;
  }

  .input {
    flex: 1;
    overflow: hidden;
  }

  .yzm {
    margin-left: 20rpx;
    color: #f0250e;

    &.disabled {
      color: #999;
    }
  }
}

.inp {
  height: 108rpx;
  font-size: 32rpx;
  width: 100%;
  border: 0;
  outline: none;
}
</style>
